package com.chat.server;

import com.chat.data.MySqlSingle;
import com.chat.entity.DataPackage;
import com.chat.entity.ServerAction;
import com.chat.entity.User;
import com.chat.mapper.UserMapper;
import com.chat.util.JwtUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

/**
 * 登录和注册服务
 * @author Yanglin
 */
public class VerifyServer implements DataPackagerServer {
    UserMapper userMapper;
    SqlSession session;

    public VerifyServer() throws IOException {
        session = MySqlSingle.getMySqlSingle().getSqlSessionFactory().openSession();
        userMapper = MySqlSingle.getMySqlSingle().getSqlSessionFactory().getConfiguration().getMapper(UserMapper.class,session);
    }

    /**
     * 登录服务
     * @param account 账号
     * @param password 密码
     * @return 成功返回token，失败返回null
     */
    public String login(String account,String password){
        User user = userMapper.login(account,password);
        if(user!=null){
            String token = JwtUtils.sign(account);
            return token;
        }
        return null;
    }

    /**
     * 注册用户
     * @param user
     */
    boolean registerUser(User user){

        if(user.isMatchRule()) {
            //插入
            userMapper.insertUser(user);
            session.commit();
            return true;
        }
        return false;
    }

    @Override
    public DataPackage run(DataPackage o) {
        switch (o.getAction()){
            case LOGIN:
            //登录验证
            System.out.println("尝试登录中!");
            if(o.getDate() instanceof User){//登录
                User user = (User) o.getDate();
                String token = login(user.getAccount(),user.getPassword());
                if(token!=null) {
                    user = userMapper.selectUserByAccount(user.getAccount());
                    DataPackage dataPackage = DataPackage.successResponse(user, ServerAction.YES);
                    dataPackage.setToken(token);
                    return dataPackage;
                }
            }
            break;

            case REGISTER:
                System.out.println("尝试注册中!");
                if(o.getDate() instanceof User){
                    if(registerUser((User) o.getDate()))
                        return DataPackage.successResponse(null);
                }
            break;
        }

        return DataPackage.failResponse(null, ServerAction.NO);
    }


}
